import { fileTransform } from '@/filters/index'
import { getFileId, filterId } from '@/filters/index'
import { validPrice } from '@/utils/validate'
const addProduct = {
    data() {
        return {
            info: {},
            nameRule: [
                { required: true, message: '请输入名称', trigger: 'blur' },
                { max: 50, message: '名称必须在50个字符以内', trigger: 'blur' }
            ],
            numberRule: [
                { required: true, message: '请输入数量', trigger: 'blur' },
                { pattern: /^[0-9]*$/, message: '只能输入整数', trigger: 'blur' }
            ],
            lengthRule: [
                { required: true, message: '请输入长', trigger: 'blur' },
                {
                    validator(rule, value, callback) {
                        validPrice(value) ?
                            callback() :
                            callback(new Error('长必须是数字且保留两位小数'))
                    },
                    trigger: 'blur'
                }
            ],
            hedgePriceRule: [
                { required: true, message: '请输入保值', trigger: 'blur' },
                {
                    validator(rule, value, callback) {
                        validPrice(value) ?
                            callback() :
                            callback(new Error('保值必须是数字且保留两位小数'))
                    },
                    trigger: 'blur'
                }
            ],
            widthRule: [
                { required: true, message: '请输入宽', trigger: 'blur' },
                {
                    validator(rule, value, callback) {
                        validPrice(value) ?
                            callback() :
                            callback(new Error('宽必须是数字且保留两位小数'))
                    },
                    trigger: 'blur'
                }
            ],
            heightRule: [
                { required: true, message: '请输入高', trigger: 'blur' },
                {
                    validator(rule, value, callback) {
                        validPrice(value) ?
                            callback() :
                            callback(new Error('高必须是数字且保留两位小数'))
                    },
                    trigger: 'blur'
                }
            ],
            weightProssASRule: [
                { required: true, message: '请输入毛重', trigger: 'blur' },
                {
                    validator(rule, value, callback) {
                        validPrice(value) ?
                            callback() :
                            callback(new Error('毛重必须是数字且保留两位小数'))
                    },
                    trigger: 'blur'
                }
            ],
            weightASRule: [
                { required: true, message: '请输入净重', trigger: 'blur' },
                {
                    validator(rule, value, callback) {
                        typeof value === 'number' ?
                            callback() :
                            callback(new Error('净重必须是数字'))
                    },
                    trigger: 'blur'
                }
            ],

            imageList: [],
            fileList: [],
            freightList: [],
            classifyList: [],
            suppierList: [],

            // 包装方式 ：1-普通商品 2-多箱包装
            splitOrderList: [{
                code: 1,
                name: '普通商品'
            },
            {
                code: 2,
                name: '多箱包装'
            }
            ],
            // 是否保价：1-保价 0-不保价
            isSurePriceList: [{
                code: 0,
                name: '不保价'
            },
            {
                code: 1,
                name: '保价'
            }
            ],
            // 运营类型：1-代营 2-自营
            operateList: [{
                code: 1,
                name: '代营'
            },
            {
                code: 2,
                name: '自营'
            }
            ],

            // 计量单位
            unitList: [],
            disabledClassify: false,
            propsClassify: {
                disabled: 'disabled' // 商品分类只能选择二级
            },
            imageAction: process.env.VUE_APP_BASE_API + '/upload/image',
            headers: {
                authorization: ''
            },
            fileListDescription: [], // 商品说明书上传
            fileListmark: [], // 箱唛上传
            fileListother: [], // 其他资料上传
            fileListpictures: [], // 整箱产品组成图片上传
            fileListdetail: [], // 产品包装细节图上传
            selectList: [],
            queryId: '',
            btnLoading: false,
            productConfig: {}, // 商品参数

            supplyParams: {
                page: 1,
                limit: 100000000,
                audit_status: 2,
                cooperation_status: 1
            },

            purchaseParams: {
                status: 1
            },

            companyParams: {
                page: 1,
                limit: 100000000,
                is_status: 1
            },

            category_code: '' // 分类 code
        }
    },

    watch: {
        // 监听分组信息，累加到包装信息里
        'form.groupDataJson': {
            handler: function (val, oldVal) {
                const vm = this
                const groupDataJson = val
                let total = {
                    length: '', // 尺寸公制(长)
                    width: '', // 尺寸公制(宽)
                    height: '', // 尺寸公制(高)
                    volume: '', // 体积
                    length_AS: '', // （美）尺寸公制(长)cm
                    width_AS: '', // （美）美制宽cm
                    height_AS: '', // （美）尺寸公制(高)cm
                    volume_AS: '', // （美）体积
                    weight_gross: '', // 毛重
                    weight_gross_AS: '', // （美）毛重 kg
                    weight: '', // 净重 kg
                    weight_AS: '', // 美制净重 kg
                    volume_weight_AS: '', // （美）体积重 体积(美制)*系数
                    oversize: '' // oversize(特大) (美制)长+（宽+高）*2
                }
                const arr = [
                    'length',
                    'width',
                    'height',
                    'volume',
                    'length_AS',
                    'weight',
                    'width_AS',
                    'height_AS',
                    'volume_AS',
                    'oversize',
                    'weight_gross',
                    'volume_weight_AS',
                    'weight_gross_AS',
                    'weight',
                    'weight_AS'
                ]
                total = groupDataJson.reduce((total, e) => {
                    if (vm.checkGroupItem(e)) {
                        // 体积
                        e.volume = vm.getVolume(e.length, e.width, e.height)
                        e.volume_AS = vm.getVolume(e.length_AS, e.width_AS, e.height_AS)
                        e.volume_weight_AS = vm.getVolumeWeight(e.length_AS, e.width_AS, e.height_AS)
                        // 体积（美）
                        // oversize
                        e.oversize = vm.getOversize(e.length_AS, e.width_AS, e.height_AS)
                        // 毛重(美制)
                        // e.weight_gross_AS = +vm.$computed.accMul(e.weight_gross, vm.weightConfig).toFixed(6)
                        arr.forEach((ele) => {
                            vm.reduceGroupKey(total, e, ele)
                        })
                    }
                    return total
                }, total)
                vm.setPackDataJson(total)
            },
            deep: true
        }
    },
    computed: {
        // 是否审核通过
        isAudited() {
            return this.info.status === 1
        },
        // 厘米  转为 英寸的 config
        lengthConfig({ productConfig }) {
            return productConfig ? productConfig.cm_to_in : 0
        },
        // kg 转为 磅
        weightConfig({ productConfig }) {
            return productConfig ? productConfig.kg_to_pt : 0
        }
    },
    created() {
        const vm = this
        vm.getUnitList() // 获取计量单位
    },
    methods: {
        // 获取 计算单位
        getUnitList() {
            const vm = this
            vm.$cache.getDic('unit').then(res => {
                vm.unitList = res
            })
        },
        // 修改size 处理函数
        sizeChange(val, index, prop) {
            const vm = this
            vm.form.groupDataJson[index][prop] = +(val * vm.lengthConfig).toFixed(6)
        },
        // 净重 美制
        weightChange(val, index, prop) {
            const vm = this
            vm.form.groupDataJson[index][prop] = +vm.$computed.accMul(val, vm.weightConfig).toFixed(6)
        },
        // 获取体积
        getVolume(length, width, height) {
            const vm = this
            // length, width, height 单位 为 cm 需要转为 m
            length = length / 100
            width = width / 100
            height = height / 100
            return +vm.$computed.accMul(length, vm.$computed.accMul(width, height)).toFixed(6)
        },
        // 获取美制体积
        getUSAVolume(length, width, height) {
            const vm = this
            // length, width, height 单位 为 cm 需要转为 m
            return +vm.$computed.accMul(length, vm.$computed.accMul(width, height)).toFixed(6)
        },
        // 获取体积重
        getVolumeWeight(length, width, height) {
            const volume = +this.$computed.accMul(length, this.$computed.accMul(width, height)).toFixed(6)
            return +(volume / this.productConfig.volume_factor).toFixed(6)
        },
        // 获取系统参数
        getProductConfig() {
            const vm = this
            vm.$http.get('/config/product').then(res => {
                vm.productConfig = res.data.product
            })
        },
        // 设置
        setPackDataJson(total) {
            const vm = this
            for (const key in total) {
                vm.form.packDataJson[0][key] = total[key]
            }
        },
        // 累加 key
        reduceGroupKey(total, e, key) {
            const vm = this
            total[key] = vm.$computed.accAdd(
                total[key],
                vm.$computed.accMul(e['number'], e[key])
            )
        },
        // 检查分组item的验证
        checkGroupItem(item) {
            const arr = [
                'name',
                'number',
                'length',
                'width',
                'height',
                'length_AS',
                'width_AS',
                'height_AS',
                'weight_gross',
                'weight_gross_AS',
                'weight',
                'weight_AS'
            ]
            return arr.every((e) => item[e])
        },
        // 获取 oversize
        getOversize(length, width, height) {
            const vm = this
            return +vm.$computed.accAdd(
                length,
                vm.$computed.accMul(vm.$computed.accAdd(width, height), 2)
            ).toFixed(6)
        },
        // 设置otherData
        setOtherData(otherData) {
            const vm = this
            if (otherData) {
                for (const key in vm.form.otherDataJson[0]) {
                    vm.form.otherDataJson[0][key] = otherData[key]
                }
                const {
                    description,
                    box_mark,
                    other,
                    pictures,
                    detail_pictures
                } = this.form.otherDataJson[0]
                this.fileListDescription = fileTransform(description)
                this.fileListmark = fileTransform(box_mark)
                this.fileListother = fileTransform(other)
                this.fileListpictures = fileTransform(pictures)
                this.fileListdetail = fileTransform(detail_pictures)
                vm.form.otherDataJson[0]['id'] = otherData.id
            }
        },
        // 设置图片信息
        setImageList() {
            const vm = this
            vm.imageList = [{
                name: vm.form.image_url,
                url: vm.form.image_url
            }]
        },
        // 设置 商品 分组 Name
        setGroupDataName(groupDataJson) {
            groupDataJson.forEach(e => {
                e.name = `${this.category_code}${e.name}`
            })
        },
        // 设置包装信息
        setPackData(packData) {
            const vm = this
            if (packData) {
                for (const key in vm.form.packDataJson[0]) {
                    vm.form.packDataJson[0][key] = packData[key]
                }
                vm.form.packDataJson[0]['id'] = packData.id
            }
        },
        // 设置分组信息
        setGroupData(groupData) {
            const vm = this
            if (groupData.length > 0) {
                vm.form.groupDataJson = groupData.map(e => {
                    const obj = {
                        id: e.id,
                        name: e.name,
                        number: e.number,
                        length: e.length,
                        width: e.width,
                        height: e.height,
                        volume: e.volume,
                        length_AS: e.length_AS,
                        width_AS: e.width_AS,
                        height_AS: e.height_AS,
                        volume_AS: e.volume_AS,
                        volume_weight_AS: e.volume_weight_AS,
                        weight_gross: e.weight_gross,
                        weight_gross_AS: e.weight_gross_AS,
                        weight: e.weight,
                        weight_AS: e.weight_AS,
                        oversize: e.oversize,
                        hedge_price: e.hedge_price
                    }
                    return obj
                })
            }
        },
        handleChangeClassify(category) {
            const vm = this
            vm.form.ZH_HS = category.ZH_HS
            vm.form.EN_HS = category.EN_HS
            vm.form.tax_rebate_rate = category.tax_rebate_rate
            vm.form.tax_tariff_rate = category.tax_tariff_rate
            vm.category_code = category.code
        },
        // 商品说明书
        handleImageDescription({ name, url }) {
            this.fileListDescription.push({ name, url })
            this.form.otherDataJson[0].description = getFileId(
                this.fileListDescription
            )
        },
        beforeRemoveFileDescription(file) {
            this.fileListDescription = filterId(this.fileListDescription, file)
            this.form.otherDataJson[0].description = getFileId(
                this.fileListDescription
            )
        },
        // 箱唛
        handleImagemark({ name, url }) {
            this.fileListmark.push({ name, url })
            this.form.otherDataJson[0].box_mark = getFileId(this.fileListmark)
        },
        beforeRemoveFilemark(file) {
            this.fileListmark = filterId(this.fileListmark, file)
            this.form.otherDataJson[0].box_mark = getFileId(this.fileListmark)
        },
        // 其他资料
        handleImageother({ name, url }) {
            this.fileListother.push({ name, url })
            this.form.otherDataJson[0].other = getFileId(this.fileListother)
        },
        beforeRemoveFileother(file) {
            this.fileListother = filterId(this.fileListother, file)
            this.form.otherDataJson[0].other = getFileId(this.fileListother)
        },
        // 整箱产品组成图片
        handleImagepictures({ name, url }) {
            this.fileListpictures.push({ name, url })
            this.form.otherDataJson[0].pictures = getFileId(this.fileListpictures)
        },
        beforeRemoveFilepictures(file) {
            this.fileListpictures = filterId(this.fileListpictures, file)
            this.form.otherDataJson[0].pictures = getFileId(this.fileListpictures)
        },
        // 产品包装细节图
        handleImagedetail({ name, url }) {
            this.fileListdetail.push({ name, url })
            this.form.otherDataJson[0].detail_pictures = getFileId(
                this.fileListdetail
            )
        },
        beforeRemoveFiledetail(file) {
            this.fileListdetail = filterId(this.fileListdetail, file)
            this.form.otherDataJson[0].detail_pictures = getFileId(
                this.fileListdetail
            )
        },
        // 修改采购员 handler
        changePurchaseHandler(e) {
            this.form.purchase_name = e.username
        },
        // 商品分组删除
        handleDelete(index, row) {
            const vm = this
            vm.form.groupDataJson.splice(index, 1)
        },
        createStateFilter(queryString) {
            return (state) => {
                return (
                    state.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
                )
            }
        },
        handleSelectBlno(data) {
            this.form.purchase_id = data.label
        },
        handleImageSuccess({ name, url }) {
            this.form.image_url = url
            this.imageList.push({ name, url })
        },
        beforeImageUpload(file) {
            this.imageList = []
        },
        addGroup() {
            this.form.groupDataJson.push({
                name: '', // 名称
                number: 1, // 数量
                length: '', // 尺寸公制(长)
                width: '', // 尺寸公制(宽)
                height: '', // 尺寸公制(高)
                volume: '', // 体积
                weight_gross: '', // 毛重
                weight: '', // 净重 kg
                length_AS: '', // （美）尺寸公制(长)cm
                width_AS: '', // 美制宽cm
                height_AS: '', // （美）尺寸公制(高)cm
                volume_AS: '', // （美）体积
                weight_AS: '', // 美制净重 kg
                weight_gross_AS: '', // （美）毛重 kg
                volume_weight_AS: '', // （美）体积重 体积(美制)*系数
                oversize: '' // oversize(特大) (美制)长+（宽+高）*2
            })
        },
        // 商品分组多选
        handleSelectionChange(val) {
            this.selectList = val
        },
        deleteGroup() {
            const that = this
            const dataLength = that.selectList.length
            if (dataLength === 0) {
                that.$message.error('最少选择一条数据')
                return false
            }
            that.selectList.forEach(function (item, index) {
                that.form.groupDataJson.forEach(function (itemI, indexI) {
                    if (item === itemI) {
                        that.form.groupDataJson.splice(indexI, 1)
                    }
                })
            })
            that.$refs.multipleTable.clearSelection()
        },
        coverNumberToString(object) {
            for (const key in object) {
                if (Object.hasOwnProperty.call(object, key)) {
                    const value = object[key]
                    if (typeof value === 'number') {
                        object[key] = value.toString()
                    } else if (object[key].toString() === '[object Object]') {
                        this.coverNumberToString(object[key])
                    }
                }
            }
            return object
        }
    }
}

export default addProduct